package com.kmproject.haifu.mvp.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.AppUtil;
import com.kmproject.haifu.di.component.DaggerHouseReportComponent;
import com.kmproject.haifu.mvp.contract.HouseReportContract;
import com.kmproject.haifu.mvp.model.entity.beans.HousePayWayBean;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.resbean.AddReportParmer;
import com.kmproject.haifu.mvp.model.entity.resbean.ImgBean;
import com.kmproject.haifu.mvp.presenter.HouseReportPresenter;
import com.kmproject.haifu.mvp.ui.adapter.AddImgAdapter;
import com.kmproject.haifu.mvp.ui.adapter.HousereportResponseAdapter;
import com.kmproject.haifu.mvp.ui.adapter.ReportImgAdapter;
import com.kmproject.haifu.mvp.ui.widget.Subject;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.SpaceItemDecoration;
import com.zhihu.matisse.Matisse;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 07/10/2019 14:04
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class HouseReportActivity extends BaseActivity<HouseReportPresenter> implements HouseReportContract.View {

    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.back_right_icon)
    ImageView backRightIcon;
    @BindView(R.id.back_right_txt)
    TextView backRightTxt;
    @BindView(R.id.toolbar_right)
    RelativeLayout toolbarRight;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    @BindView(R.id.HouseReport_RecyclerView)
    RecyclerView HouseReportRecyclerView;
    @BindView(R.id.HouseReport_edit)
    EditText HouseReportEdit;
    @BindView(R.id.HouseReport_txt_num)
    TextView HouseReportTxtNum;
    @BindView(R.id.HouseReport_RecyclerView2)
    RecyclerView HouseReportRecyclerView2;
    @BindView(R.id.HouseReport_sure_btn)
    TextView HouseReportSureBtn;
    HousereportResponseAdapter housereportResponseAdapter;
    private ReportImgAdapter addImgAdapter;
    private List<Subject> datas = new ArrayList<>();
    List<AddReportParmer.ReportImg> reportImgs=new ArrayList<>();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerHouseReportComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_house_report; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        HouseReportRecyclerView.setLayoutManager(new FlowLayoutManager());
        HouseReportRecyclerView.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(4)));
        housereportResponseAdapter=new HousereportResponseAdapter(new ArrayList<>(), new HousereportResponseAdapter.ClickItemCallback() {
            @Override
            public void callBack(int index) {
                setBtnStatus(true);
            }
        });
        HouseReportRecyclerView.setAdapter(housereportResponseAdapter);

        HouseReportRecyclerView2.setLayoutManager(new GridLayoutManager(this, 3));
        List<Subject> temData=new ArrayList<>();
        temData.add(null);
        addImgAdapter = new ReportImgAdapter(temData);
        HouseReportRecyclerView2.addItemDecoration(new SpaceItemDecoration(AppUtil.dp2px(2)));
        HouseReportRecyclerView2.setAdapter(addImgAdapter);
        setBtnStatus(false);
        HouseReportEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
             if (s!=null&&s.length()<801)
             {
                 HouseReportTxtNum.setText(s.length()+"/800");
                 setBtnStatus(true);
             }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.getHousePayWayBean();
    }

    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void getHousePayWayBeanSuccess(List<HousePayWayBean> housePayWayBeans) {
        housereportResponseAdapter.setNewData(housePayWayBeans);
    }

    @Override
    public void addReportSuccess() {

        AppUtil.midToast(AppManager.getAppManager().getCurrentActivity(),"举报成功我们会认值核实处理净化平台环境");
        killMyself();
    }

        @Override
    public void updateImgSuccess(int index, String sercerPath) {
        datas.get(index).setServerPath(sercerPath);
            reportImgs.add(new AddReportParmer.ReportImg(sercerPath, sercerPath.substring(sercerPath.lastIndexOf(".") + 1, sercerPath.length()),index));
        if (datas.size() - 1 > index) {
            mPresenter.updateHeadImg(index + 1, datas.get(index + 1));
        } else {
            //上传成功
            updateData();

        }
    }

    /**
     * 提交数据
     */
    public void updateData()
    {
        /**
         * 举报方式
         */

        AddReportParmer addReportParmer=new AddReportParmer();
        addReportParmer.setUserReportImage(reportImgs);
        addReportParmer.setReportReason(housereportResponseAdapter.getData().get(housereportResponseAdapter.getSelectInde()).getDictId());
        addReportParmer.setIsAvailable("1");
        addReportParmer.setIsVerify("1");
        addReportParmer.setReportDetail(HouseReportEdit.getText().toString().toString());
       if (getIntent().hasExtra("rentId"))
       {
           addReportParmer.setReportTableId(getIntent().getStringExtra("rentId"));
       }
        if (getIntent().hasExtra("reportUserId"))
        {
            addReportParmer.setReportUserId(getIntent().getStringExtra("reportUserId"));
        }
        if (getIntent().hasExtra("reportType"))
        {
            addReportParmer.setReportType(getIntent().getStringExtra("reportType"));
        }

        UserBean userBean = DataHelper.getDeviceData(this, AppConstant.USER_INFO);//获取用户信息
        if (userBean!=null)
        {
            addReportParmer.setUserId(userBean.getUserId());
        }

        mPresenter.addReport(addReportParmer);
    }
    @Override
    public void updateImgFail(int index) {
        mPresenter.updateHeadImg(index, datas.get(index));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.HouseReport_sure_btn)
    public void onClick() {

        if(housereportResponseAdapter.getSelectInde()==-1)
        {
            showMessage("请选择举报原因");
            return;
        }
        if (HouseReportEdit.getText().toString().length()<1)
        {

            showMessage("请输入描述");
            return;
        }
        if (!datas.isEmpty())
        {
            mPresenter.updateHeadImg(0, datas.get(0));
        }else {
            updateData();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null && requestCode == AppConstant.REQUEST_CODE_CHOOSE) {
            List<Uri> temSelected=Matisse.obtainResult(data);
            if (temSelected!=null&&!temSelected.isEmpty())
            {
                YsImg(temSelected);
            }
        }

    }

    public void YsImg(final List<Uri> temmSelected) {
        if (temmSelected != null && !temmSelected.isEmpty()) {
            for (int i = 0; i < temmSelected.size(); i++) {
                AppUtil.getBitmapFromUri(this, temmSelected.get(i));
                String path = AppUtil.getFromMediaUri(this, getContentResolver(), temmSelected.get(i));
                if (!TextUtils.isEmpty(path)) {
                    File file = new File(path);
                    if (file != null && file.exists()) {
                        Luban.with(this)
                                .load(file)
                                .ignoreBy(100)
                                //                                .setTargetDir()
                                .filter(new CompressionPredicate() {
                                    @Override
                                    public boolean apply(String path) {
                                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                                    }
                                })
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart() {
                                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                                    }

                                    @Override
                                    public void onSuccess(File file) {
                                        // TODO 压缩成功后调用，返回压缩后的图片文件
                                        //上传图片
                                        if (datas.size() > 5) {
                                            showMessage("最多只能选择5图片");
                                            return;
                                        }
                                         setBtnStatus(true);
                                            datas.add(new Subject(file, file.getPath()));
                                            referView();
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        // TODO 当压缩过程出现问题时调用
                                    }

                                }).launch();

                    }
                }
            }
        }

    }

    /**
     * 刷新数据
     */
    public void referView()
    {

        List<Subject> temPath=new ArrayList<>();
        if (datas.size()>1)
        {
            for (int i=1;i<datas.size();i++)
            {
                temPath.add(datas.get(i));
            }
        }
        temPath.add(null);//最后一个
        addImgAdapter.setNewData(temPath);

    }

    /**
     * 设置登录按钮状态
     * @param isClick
     */
    public void setBtnStatus(boolean isClick)
    {
        if (HouseReportSureBtn!=null)
        {
            if (isClick)
            {
                HouseReportSureBtn.setEnabled(true);
                HouseReportSureBtn.setBackgroundResource(R.drawable.button_yellow_bg);
                HouseReportSureBtn.setTextColor(getResources().getColor(R.color.color_191919));
            }else {
                HouseReportSureBtn.setEnabled(false);
                HouseReportSureBtn.setBackgroundResource(R.drawable.button_gray_bg);
                HouseReportSureBtn.setTextColor(getResources().getColor(R.color.color_EDEDED));
            }
        }
    }
}
